package com.example.ytyproject.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ytyproject.entity.Censuspaper;
import com.example.ytyproject.mapper.CensuspaperMapper;
import com.example.ytyproject.service.ICensuspaperService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yg
 * @since 2023-11-20
 */
@Service
public class CensuspaperServiceImpl extends ServiceImpl<CensuspaperMapper, Censuspaper> implements ICensuspaperService {

    @Override
    public void importRepayReconciliate(InputStream inputStream, HttpServletRequest request) throws Exception{
        long s1 = System.currentTimeMillis();

        Workbook book = WorkbookFactory.create(inputStream); //创建工作簿
        Sheet sheet = book.getSheetAt(0);//获取到工作表
        int lastRowNum = sheet.getLastRowNum();//获取到表格最后一行
        if (lastRowNum < 1 ) {
            throw new Exception("你未导入任何数据，请添加数据后导入...");
        }
        // 获取导入的数据
        List<Censuspaper> list = getCenSusPaperInportData(sheet);
        List<String> idcards = list.stream().map(Censuspaper::getCardId).distinct().collect(Collectors.toList());
        if (!idcards.isEmpty()) {
            QueryWrapper<Censuspaper> queryWrapper = new QueryWrapper<Censuspaper>();
            LambdaQueryWrapper<Censuspaper> lambda = queryWrapper.lambda();
            lambda.in(Censuspaper::getCardId, idcards);
            List<Censuspaper> queryList = list(lambda);
            if (!queryList.isEmpty()) {
                List<String> ids = queryList.stream().map(Censuspaper::getId).collect(Collectors.toList());
                this.removeByIds(ids);
            }
        }
        // 新增的数据
        this.saveBatch(list);

        long s2 = System.currentTimeMillis();
        System.out.println("***********总共耗时（s）：*****************" + (s2-s1)/1000);
    }

    private List<Censuspaper> getCenSusPaperInportData(Sheet sheet) {
        int lastRowNum = sheet.getLastRowNum();
        // 存储所有数据
        List<Censuspaper> results = new ArrayList<>();
        // 获取所有行的标题字段
        List<String> storageFields = getStorageFields(sheet);
        for (int rowIndex = 2; rowIndex <= lastRowNum; rowIndex++) {
            JSONObject jsonObject = new JSONObject();
            Row row = sheet.getRow(rowIndex);
            for (int i = 0; i < storageFields.size(); i++) {
                Cell cell = row.getCell(i);
//                cell.setCellType(CellType.STRING);
                String value = new DataFormatter().formatCellValue(cell);
                jsonObject.put(storageFields.get(i), value);
            }
            Censuspaper cenSusPaper = JSONObject.toJavaObject(jsonObject, Censuspaper.class);
            cenSusPaper.setCreateDate(LocalDateTime.now());
            cenSusPaper.setCreateBy("111");
            cenSusPaper.setRemark("2222");
            cenSusPaper.setBirthday(LocalDateTime.now());
            results.add(cenSusPaper);
        }
        return results;
    }

    private List<String> getStorageFields(Sheet sheet) {
        Row row = sheet.getRow(1);
        int cellIndex = 0;
        List<String> list = new ArrayList<>();
        while (true) {
            Cell cell = row.getCell(cellIndex);
            if (cell == null) {
                break;
            }
            String value = cell.getStringCellValue();
            if (StringUtils.isEmpty(value)) {
                break;
            }
            String str = lineToHump(value);
            list.add(str);
            cellIndex ++;
        }
        return list;
    }


    private static final Pattern linePattern = Pattern.compile("_(\\w)");


    /**
     * 下划线转驼峰
     * @param str 字符串
     * @return 转换后的字符串
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
